package com.qf.Service.Impl;/*
 *
 */

import com.qf.Dao.Impl.OrderDaoImpl;
import com.qf.Dao.OrderDao;
import com.qf.Domain.Cart;
import com.qf.Domain.Goods;
import com.qf.Domain.Order;
import com.qf.Domain.OrderDetail;
import com.qf.Service.CartsService;
import com.qf.Service.GoodService;
import com.qf.Service.OrderService;
import com.qf.Utils.DataSourceUtils;
import com.qf.Utils.RandomUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao=new OrderDaoImpl();
    @Override
    public Order addOrder(Integer uid, int aid, List<Cart> carts) {
        //三张表进行操作
        try {
            DataSourceUtils.startAutoCommit();
            //1、向订单表添加数据
            BigDecimal sum=new BigDecimal(0);
            //创建集合保存订单详情
            ArrayList<OrderDetail> detailArrayList=new ArrayList<>();
            String oid=RandomUtils.createOrderId();
            for (Cart cart : carts) {
                sum=sum.add(cart.getMoney());
                detailArrayList.add(new OrderDetail(0, oid, cart.getPid(), cart.getNum(), cart.getMoney()));
            }
            //订单的四个状态 1：未提交  2、提交未付款 3、付款未发货 4、订单已完成

            Order order=new Order(oid, uid, sum, "1", new Date(), aid);
            OrderDao orderDao=new OrderDaoImpl();
            orderDao.insert(order);
            //2、向订单详情表中添加数据
            for (OrderDetail orderDetail : detailArrayList) {
                orderDao.insertDetail(orderDetail);
            }
            //3、清空购物车
            CartsService cartsService=new CartServiceImpl();
            cartsService.delete(uid);
            DataSourceUtils.commit();
            return order;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DataSourceUtils.rollback();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DataSourceUtils.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void updateStatus(String oid, String status) {
        orderDao.update(oid,status);
    }

    @Override
    public List<Order> findByOid(Integer uid) {
        return orderDao.selectByOid(uid);
    }

    @Override
    public Order findById(String oid) {
        return orderDao.selectById(oid);
    }

    @Override
    public List<OrderDetail> findDetail(String oid) {
        List<OrderDetail> orderDetails = orderDao.selectDetail(oid);
        if (orderDetails!=null){
            GoodService goodService=new GoodsServiceImpl();
            for (OrderDetail orderDetail : orderDetails) {
                Goods goods = goodService.fingById(orderDetail.getPid());
                orderDetail.setGoods(goods);
            }
        }
        return orderDetails;
    }
}
